import {Component, OnInit} from '@angular/core';
import {FetchService} from "../../../core/net/fetch.service";
import * as _ from 'lodash';
import 'echarts-liquidfill';
import {NzMessageService} from "ng-zorro-antd";

const modalTitleArr = [
    '干渠进口水位流量报送情况',
    '灌溉进度报送情况',
    '湖泊湿地补水进度报送情况',
    // '工业用水报送情况',
    '用水量进度报送情况',
    '月度水情报送情况',
    // '灌区运行状态（水位流量指标）',
    // '灌区运行状态（引水计划指标）'
];
const smsTitleArr = [
    '干渠进口水位流量',
    '灌溉进度',
    '湖泊湿地补水进度',
    // '工业用水',
    '用水量进度',
    '月度水情',
    // '灌区运行（水位流量指标）',
    // '灌区运行（引水计划指标）'
];
const tableHeadArr = [
    ['管理处', '时段', '报送状态'],
    ['管理处', '报送状态'],
    ['管理处', '正常运行', '异常运行'],
];

/**
 * 一键催报url列表
 */
const reportUrls = {
    0: 'muw/submit/reportWf',
    1: 'muw/submit/reportIrr',
    2: 'muw/submit/reportLw',
    3: 'muw/submit/reportIrr',
    4: ''
};

@Component({
    selector: 'app-overview',
    templateUrl: './overview.component.html',
    styleUrls: ['./overview.component.scss']
})
export class OverviewComponent implements OnInit {

    inletFinishedNum = 0;
    inletUnfinishedNum = 0;
    inletPercentage = 0;
    inletData = [];
    inletChartOption: any = {};

    irrigateFinishedNum = 0;
    irrigateUnfinishedNum = 0;
    irrigatePercentage = 0;
    irrigateData = [];
    irrigateChartOption: any = {};

    lakeFinishedNum = 0;
    lakeUnfinishedNum = 0;
    lakePercentage = 0;
    lakeData = [];
    lakeChartOption: any = {};

    waterUsageFinishedNum = 0;
    waterUsageUnfinishedNum = 0;
    waterUsagePercentage = 0;
    waterUsageData = [];
    waterUsageChartOption: any = {};

    industrialFinishedNum = 0;
    industrialUnfinishedNum = 0;
    industrialPercentage = 0;
    industrialData = [];
    industrialChartOption: any = {};

    monthlyFinishedNum = 0;
    monthlyUnfinishedNum = 0;
    monthlyPercentage = 0;
    monthlyData = [];
    monthlyChartOption: any = {};

    irrRunData = [];
    irrRunTotal = {
        normal: 0,
        abnormal: 0
    };
    data = 89;
    liquidChartOption = {
        series: [
            {
                name: "正常运行",
                type: 'liquidFill',
                data: [],
                radius: "80%",
                outline: {
                    show: true,
                    borderDistance: 0,
                    itemStyle: {
                        borderColor: "#edf2f6",
                        borderWidth: 1
                    }
                },
                label: {
                    normal: {
                        textStyle: {
                            color: 'white',  // 默认背景下的文字颜色
                            insideColor: 'white', // 水波背景下的文字颜色
                            fontWeight: 'normal',
                            fontSize: 16   // 字体大小
                        },
                        rich: {
                            a: {
                                fontSize: 16,
                                lineHeight: 16,
                                fontWeight: "bold"
                            },
                            b: {
                                fontSize: 16,
                                lineHeight: 16,
                                fontWeight: "bold"
                            }
                        }
                    }
                }
            }
        ]
    };
    greenLiquidOption = {};
    blueLiquidOption = {};

    irrBaseChartOpt = {
        legend: { data: ['累计用水量', '灌溉面积']},
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        color: ['#d0e3fe', '#69c0fe', '#003366', '#bad578', '#cdcbcc'],
        xAxis: {
            type: 'category',
            axisLabel: {
                interval: 0
            },
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            }
        },
        yAxis: {
            show: false
        },
        barMaxWidth: '30%',
        series: [
            {type: 'bar'},
            {type: 'bar'}
        ]
    };
    irrProgressDataChartOpt = {};
    processBaseChartOption = {
        color: ['#6084fd', '#8abe78', '#69c0fe'],
        grid: {
            top: 5,
            left: '3%',
            right: '3%',
            bottom: 5,
            containLabel: true
        },
        xAxis: {
            type: 'value',
            show: false,
            max: 100,
            splitLine: {
                show: false
            }
        },
        yAxis: {
            type: 'category',
            data: [],
            axisLabel: {
                interval: 0
            },
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            splitLine: {
                show: false
            }
        },
        series: [
            {
                type: 'bar',
                stack: 'process',
                barWidth: '40%',
                z: 3,
                label: {
                    normal: {
                        position: 'right',
                        formatter: '{c}%',
                        show: true
                    },
                },
                itemStyle: {
                    color: params => {
                        const colorList = ['#6084fd', '#8abe78', '#69c0fe'];
                        return colorList[params.dataIndex % 3];
                    }
                },
                data: []
            },
            {
                type: 'bar',
                stack: 'process',
                barWidth: '50%',
                silent: true,
                itemStyle: {
                    normal: {
                        color: '#e3e3e3'
                    }
                },
                data: []
            }
        ]
    };
    processChartOpt = {};
    detailIrrigateChartOption = {
        grid: {
            top: 10,
            left: '5%',
            right: '15%',
            bottom: 10,
            containLabel: true
        },
        xAxis: {
            type: 'value',
            show: false,
            splitLine: {
                show: false
            }
        },
        yAxis: {
            type: 'category',
            data: [],
            axisLabel: {
                interval: 0
            },
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            splitLine: {
                show: false
            }
        },
        series: [
            {
                type: 'bar',
                barWidth: '40%',
                z: 3,
                label: {
                    normal: {
                        position: 'right',
                        formatter: '{c}',
                        show: true
                    },
                },
                itemStyle: {
                    color: params => {
                        const colorList = ['#6084fd', '#8abe78', '#69c0fe'];
                        return colorList[params.dataIndex % 3];
                    }
                },
                data: []
            }
        ]
    };

    lakeDetailList = [];
    modalTitle: string = '';
    smsTitle: string = '';
    modalShow: boolean = false;
    pageIndex = 1;
    tableType = 0;

    tableData = [];
    tableData1 = [];
    tableData2 = [];
    headData = [];

    currentCardIdx = 0;
    detailTitle = '干渠进口水位流量报送详情';
    constructor(private fetchService: FetchService,
                private message: NzMessageService) {
    }

    ngOnInit() {
        this.getInletData();
        this.getIrrigateData();
        this.getLakeData();
        this.getWaterUsageData();
        // this.getIndustrialData();
        this.getMonthlyData();
        // this.getIrrRunData();
        // this.getIrrProgressData();
        // this.getLakeDetailProgress();
        this.blueLiquidOption = {
            series: [
                {
                    data: [
                        0,
                        0
                    ],
                    label: {
                        normal: {
                            formatter: "{a|" +
                                "正常运行" +
                                "}" +
                                "\n" +
                                "\n" +
                                "{b|" + '0' + "%" +
                                '}'
                        }
                    },
                    color: ['#6cadef', '#ACC8EF']
                }
            ]
        };

    }

    formatPercentage = (percent: number) => ``;

    // 干渠进口水位流量环形图
    getInletData(): void {
        this.fetchService.get<any>('muw/submit/querySubmitWf').subscribe(res => {
            if (res) {
                const finalData: GeneralData = this.calcInfoData(res);
                this.inletFinishedNum = finalData.finished;
                this.inletUnfinishedNum = finalData.unfinished;
                this.inletPercentage = finalData.percentage;
                this.inletChartOption = {
                    title: {
                        text: '报送进度\n\n ' + this.inletPercentage,
                    },
                    color: ['#3398DB', '#ddd'],
                    series: [
                        {
                            data: [
                                {
                                    value: this.inletFinishedNum
                                }, {
                                    value: this.inletUnfinishedNum
                                }
                            ]
                        }
                    ]
                };
                res.forEach(item => {
                    item['status'] = item.statu === 1 ? '未报送' : '已报送';
                    item['hour'] = item.hour && `${item.hour}h`;
                });
                this.inletData = _.sortBy(res, o => {
                    return o.statu;
                });
                this.openModal(0, 0);
            }
        });
    }

    // 灌溉进度环形图
    getIrrigateData(): void {
        this.fetchService.post<any>('muw/submit/querySubmitIrr', {}).subscribe(res => {
            if (res) {
                const finalData: GeneralData = this.calcInfoData(res);
                this.irrigateFinishedNum = finalData.finished;
                this.irrigateUnfinishedNum = finalData.unfinished;
                this.irrigatePercentage = finalData.percentage;
                this.irrigateChartOption = {
                    title: {
                        text: '报送进度\n\n ' + this.irrigatePercentage,
                    },
                    color: ['#FFE535', '#ddd'],
                    series: [
                        {
                            data: [
                                {
                                    value: this.irrigateFinishedNum
                                }, {
                                    value: this.irrigateUnfinishedNum
                                }
                            ]
                        }
                    ]
                };
                res.forEach(item => {
                    item['status'] = item.statu === 1 ? '未报送' : '已报送';
                });
                this.irrigateData = _.sortBy(res, o => {
                    return o.statu;
                });
            }
        });
    }

    // 湖泊环形图
    getLakeData(): void {
        this.fetchService.get<any>('muw/submit/querySubmitLw').subscribe(res => {
            if (res) {
                const finalData: GeneralData = this.calcInfoData(res.data);
                this.lakeFinishedNum = finalData.finished;
                this.lakeUnfinishedNum = finalData.unfinished;
                this.lakePercentage = finalData.percentage;
                this.lakeChartOption = {
                    title: {
                        text: '报送进度\n\n ' + this.lakePercentage,
                    },
                    color: ['#79AB40', '#ddd'],
                    series: [
                        {
                            data: [
                                {
                                    value: this.lakeFinishedNum
                                }, {
                                    value: this.lakeUnfinishedNum
                                }
                            ]
                        }
                    ]
                };
                res.data.forEach(item => {
                    item['status'] = item.statu === 1 ? '未报送' : '已报送';
                });
                this.lakeData = _.sortBy(res.data, o => {
                    return o.statu;
                });
            }
        });
    }

    // 用水量环形图
    getWaterUsageData(): void {
        this.fetchService.post<any>('muw/submit/querySubmitIrr', {type: 3}).subscribe(res => {
            if (res) {
                const finalData: GeneralData = this.calcInfoData(res);
                this.waterUsageFinishedNum = finalData.finished;
                this.waterUsageUnfinishedNum = finalData.unfinished;
                this.waterUsagePercentage = finalData.percentage;
                this.waterUsageChartOption = {
                    title: {
                        text: '报送进度\n\n ' + this.waterUsagePercentage,
                    },
                    color: ['#79AB40', '#ddd'],
                    series: [
                        {
                            data: [
                                {
                                    value: this.waterUsageFinishedNum
                                }, {
                                    value: this.waterUsageUnfinishedNum
                                }
                            ]
                        }
                    ]
                };
                res.forEach(item => {
                    item['status'] = item.statu === 1 ? '未报送' : '已报送';
                });
                this.waterUsageData = _.sortBy(res, o => {
                    return o.statu;
                });
            }
        });
    }

    // 工业用水环形图
    getIndustrialData(): void {
        this.fetchService.get<any>('muw/submit/querySubmitInd').subscribe(res => {
            if (res) {
                const finalData: GeneralData = this.calcInfoData(res);
                this.industrialFinishedNum = finalData.finished;
                this.industrialUnfinishedNum = finalData.unfinished;
                this.industrialPercentage = finalData.percentage;
                this.industrialChartOption = {
                    title: {
                        text: '报送进度\n\n ' + this.industrialPercentage,
                    },
                    color: ['#025D1A', '#ddd'],
                    series: [
                        {
                            data: [
                                {
                                    value: this.industrialFinishedNum
                                }, {
                                    value: this.industrialUnfinishedNum
                                }
                            ]
                        }
                    ]
                };
                res.forEach(item => {
                    item['status'] = item.statu === 1 ? '未报送' : '已报送';
                });
                this.industrialData = _.sortBy(res, o => {
                    return o.statu;
                });
            }
        });
    }

    // 月度水情环形图
    getMonthlyData(): void {
        this.fetchService.get<any>('muw/submit/querySubmitWr').subscribe(res => {
            if (res) {
                const finalData: GeneralData = this.calcInfoData(res);
                this.monthlyFinishedNum = finalData.finished;
                this.monthlyUnfinishedNum = finalData.unfinished;
                this.monthlyPercentage = finalData.percentage;
                this.monthlyChartOption = {
                    title: {
                        text: '报送进度\n\n ' + this.monthlyPercentage,
                    },
                    color: ['#BC7200', '#ddd'],
                    series: [
                        {
                            data: [
                                {
                                    value: this.monthlyFinishedNum
                                }, {
                                    value: this.monthlyUnfinishedNum
                                }
                            ]
                        }
                    ]
                };
                res.forEach(item => {
                    item['status'] = item.statu === 1 ? '未报送' : '已报送';
                });
                this.monthlyData = _.sortBy(res, o => {
                    return o.statu;
                });
            }
        });
    }

    private calcInfoData(list): GeneralData {
        const group = _.groupBy(list, 'statu');
        const finishedNum = group['2'] ? group['2'].length : 0;
        const unfinishedNum = group['1'] ? group['1'].length : 0;
        const percentage = list.length === 0 ? 0 : Math.round(finishedNum / list.length * 100);
        return {
            finished: finishedNum,
            unfinished: unfinishedNum,
            percentage: percentage
        };
    }


    //  灌区运行状态
    getIrrRunData(): void {
        this.fetchService.get<any>('muw/submit/queryOperStatu').subscribe(res => {
            if (res) {
                res.forEach(item => {
                    item['statu'] = item.unnormalNum === 0 ? 2 : 1;
                });
                const normalTotal = res.reduce((result, val) => {
                    result += parseFloat(val.normalNum || '0');
                    return result;
                }, 0);
                const abnormalTotal = res.reduce((result, val) => {
                    result += parseFloat(val.unnormalNum || '0');
                    return result;
                }, 0);
                this.irrRunTotal = {
                    normal: normalTotal,
                    abnormal: abnormalTotal
                };
                const percentage = normalTotal / (normalTotal + abnormalTotal);
                this.greenLiquidOption = {
                    series: [
                        {
                            data: [
                                percentage,
                                percentage,
                            ],
                            label: {
                                normal: {
                                    formatter: "{a|" +
                                        "正常运行" +
                                        "}" +
                                        "\n" +
                                        "\n" +
                                        "{b|" + percentage * 100 + "%" +
                                        '}'
                                }
                            },
                            color: ['#42BC9F', '#6DBC9D']
                        }
                    ]
                };
                this.irrRunData = _.sortBy(res, o => {
                    return o.unnormalNum;
                });
            }
        });
    }

    //  灌溉进度
    getIrrProgressData(): void {
        this.fetchService.get<any>('muw/submit/queryIrrData').subscribe(res => {
            if (res) {
                this.irrProgressDataChartOpt = {
                    xAxis: {
                        data: res.map(item => {
                            return item.manageName;
                        })
                    },
                    series: [
                        {
                            name: '累计用水量',
                            type: 'bar',
                            data: res.map(item => {
                                return item.mwo;
                            })
                        },
                        {
                            name: '灌溉面积',
                            type: 'bar',
                            data: res.map(item => {
                                return item.irrArea;
                            })
                        }
                    ]
                };
            }
        });
    }

    //  湖泊湿地补水 指标
    getLakeDetailProgress(): void {
        this.fetchService.get<any>('muw/submit/queryLwData').subscribe(res => {
            if (res) {
                this.processChartOpt = {
                    yAxis: {
                        data: res.result.map(item => {
                            return item.manageName;
                        })
                    },
                    series: [
                        {
                            type: 'bar',
                            stack: 'process',
                            data: res.result.map(item => {
                                return item.progress * 100;
                            })
                        },
                        {
                            type: 'bar',
                            stack: 'process',
                            data: res.result.map(item => {
                                return (1 - item.progress) * 100;
                            })
                        }
                    ]
                };

                const group = _.groupBy(res.data, 'manageName');
                this.lakeDetailList = Object.values(group).map((item, index) => {
                    return {
                        trName: Object.keys(group)[index],
                        lakeOpt: {
                            yAxis: {
                                data: item.map(o => {
                                    return o.prName;
                                }),
                            },
                            series: [
                                {
                                    data: item.map(o => {
                                        return o.val;
                                    })
                                }
                            ]
                        }
                    };
                });
            }
        });
    }
    openModal(idx: number, tableType: number): void {
        this.currentCardIdx = idx;
        // const dataArr = [
        //     this.inletData, this.irrigateData, this.lakeData, this.industrialData, this.monthlyData, this.irrRunData
        // ];
        const dataArr = [
            this.inletData, this.irrigateData, this.lakeData, this.waterUsageData, this.monthlyData
        ];
        // this.modalTitle = modalTitleArr[idx];
        this.detailTitle = modalTitleArr[idx];
        this.smsTitle = smsTitleArr[idx];
        this.tableType = tableType;
        this.headData = tableHeadArr[tableType];
        this.modalShow = true;
        this.tableData = dataArr[idx];
        this.tableData1 = _.chunk(dataArr[idx], Math.ceil(dataArr[idx].length / 2))[0];
        this.tableData2 = _.chunk(dataArr[idx], Math.ceil(dataArr[idx].length / 2))[1];
        // console.log(this.tableData1, this.tableData2);
    }

    closeModal() {
        this.modalShow = false;
        this.pageIndex = 1;
    }

    broadcast(data) {
        const content = `请及时提交${data.hour ? data.hour + 'h' : ''}${this.smsTitle}数据`;
        // console.log(content);
        this.fetchService
            .post("sms/publish/sendMsg", {
                content: content
            })
            .subscribe(res => {
                this.message.success('通知消息已以短信形式下发到相应管理处！');
            });
    }

    broadcastAll(): void {
        const params = this.currentCardIdx === 3 ? { type: 3 } : {};
        this.fetchService
            .post(reportUrls[this.currentCardIdx], params)
            .subscribe(res => {
                this.message.success(`${this.smsTitle}数据已催报`);
            });
    }
}

class GeneralData {
    finished: number;
    unfinished: number;
    percentage: number;
}
